//
//  ChangePassWordViewController.m
//  MovieDate
//
//  Created by ann on 16/3/11.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "ChangePassWordViewController.h"
#import "AppDelegate.h"

@interface ChangePassWordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTXF;
@property (weak, nonatomic) IBOutlet UITextField *phoneAuthCodeTXF;

@property (weak, nonatomic) IBOutlet UITextField *passWordTXF;

@property (weak, nonatomic) IBOutlet UITextField *secondPassWordTXF;

@property (weak, nonatomic) IBOutlet UIButton *sendTestCodeBTN;

@property (weak, nonatomic) IBOutlet UIButton *okChangeBTN;

@end

@implementation ChangePassWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    

}

-(void)initView{
    self.okChangeBTN.backgroundColor = [UIColor grayColor];
    
    self.phoneAuthCodeTXF.delegate = self;

    [self.sendTestCodeBTN addTarget: self action:@selector(clickSendTestCodeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self selDefaultNavigationBackground];
    [self selDefaultNavigationWithTitle:@"修改密码"];
    [self selAddLeftBackButton];
    
    self.okChangeBTN.userInteractionEnabled = NO;

}

-(void)clickSendTestCodeAction:(UIButton *)btn{
 
    NSString *numb = [self valiMobile:self.phoneNumberTXF.text];
    if (numb.length == 11) {
        self.sendTestCodeBTN.backgroundColor = [UIColor grayColor];

        [TDNetwork sendDynCodePostURL:sendDynCodeIP andPhoneNumber:self.phoneNumberTXF.text andType:@"2" complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if ([ret isEqualToString:@"1"]){
                
                self.okChangeBTN.userInteractionEnabled = YES;
                self.okChangeBTN.backgroundColor =[UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
                
            }else if ([ret isEqualToString:@"-1"]){
              
                }else{
               
                
            }
        }];
        __block int timeout=60; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self.sendTestCodeBTN setTitle:@"获取验证码" forState:UIControlStateNormal];
                    self.sendTestCodeBTN.backgroundColor = [UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
                    self.sendTestCodeBTN.userInteractionEnabled = YES;
                });
            }else{
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置界面的按钮显示 根据自己需求设置
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:1];
                    [self.sendTestCodeBTN setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                    [UIView commitAnimations];
                    self.sendTestCodeBTN.userInteractionEnabled = NO;
                });
                timeout--;
                
            }
        });
        dispatch_resume(_timer);
    }
}
//判断是否是手机号
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
                return @"手机号11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return mobile;
        }else{
            return @"请输入有效手机号";
        }
    }
    return nil;
}

- (IBAction)clickOKchangePassWordBTN:(id)sender {
    [SVProgressHUD show];
    [TDNetwork  changePasswordPostURL:changePasswordIP andphoneNumber:self.phoneNumberTXF.text andCode:self.phoneAuthCodeTXF.text andPwd:self.passWordTXF.text complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
       
        if (succeed ) {
            if ([self.passWordTXF.text isEqualToString:self.secondPassWordTXF.text]||self.passWordTXF.text.length >5 ) {
                switch ([ret intValue]) {
                    case 1:
                        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        break;
                    case 2:
                        [SVProgressHUD showErrorWithStatus:@"手机号不正确"];
                        break;
                    case -1:
                        [SVProgressHUD showErrorWithStatus:@"账号已经注册"];
                        break;
                    case -2:
                        [SVProgressHUD showErrorWithStatus:@"验证码不正确"];
                        break;
                    case -3:
                        [SVProgressHUD showErrorWithStatus:@"验证码超时 3分钟"];
                        break;
                    case -4:
                        [SVProgressHUD showErrorWithStatus:@"手机号或者验证码（为空）不正确"];
                        break;
                    default:
                        
                        [SVProgressHUD showErrorWithStatus:@"未知错误"];
                        break;
                }

            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络请求错误"];
        }
        
    }];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.phoneNumberTXF resignFirstResponder];
    [self.phoneAuthCodeTXF resignFirstResponder];
    [self.passWordTXF resignFirstResponder];
    [self.secondPassWordTXF resignFirstResponder];
}
//#pragma -mark UITextFieldDelegate
//-(void)textFieldDidEndEditing:(UITextField *)textField{
//    
//    if (self.phoneNumberTXF.text.length ==11) {
//        self.okChangeBTN.backgroundColor = [UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
//    }
//}
//-(void)textFieldDidBeginEditing:(UITextField *)textField{
//    self.okChangeBTN.backgroundColor = [UIColor grayColor];
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
